/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@Unique(['LEMMA'])
@HasMany(['WordIndex'])
public class Word {

    String lemma
    
    @Size(2048)
    String comment

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof Word && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE Word (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT WORD_PK PRIMARY KEY, Lemma VARCHAR(255) NOT NULL, Comment VARCHAR(2048) NOT NULL)")
        
        execute('CREATE UNIQUE INDEX UIX_LEMMA__WORD ON Word (LEMMA)')
        
    }

    boolean isValid() {
        lemma?.size() <= 255 && comment?.size() <= 2048
    }


    boolean isConflicted() {
    
        def idUIX_LEMMA = findIdByUIX_LEMMA(lEMMA)
        if(idUIX_LEMMA != null && idUIX_LEMMA != id) return true
    
        false
    }

    
    Integer findIdByUIX_LEMMA(lEMMA) {
        firstRow("SELECT ID FROM Word WHERE LEMMA = $lEMMA")?.id
    }
    


    static Word create(lemma, comment) {
        def instance = new Word(lemma: lemma, comment: comment)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO Word (Lemma, Comment) VALUES (${lemma}, ${comment})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static Word find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM Word WHERE Id = $id")
        
        row ? new Word(id: row.Id, lemma: row.lemma, comment: row.comment) : null
        
    }

    static ArrayList<Word> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new Word(id: row.Id, lemma: row.lemma, comment: row.comment)
        }
        
        rows
    }

    static ArrayList<Word> findAll() {
        findBySql('SELECT * FROM Word')
    }

    
    static ArrayList<Word> findAll(String keyword) {
        findBySql("SELECT * FROM Word WHERE (Lemma LIKE $keyword) or (Comment LIKE $keyword)")
    }
    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE Word SET Lemma = ${lemma}, Comment = ${comment} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM Word WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<Word> findByLemma(value) {
        findBySql("SELECT * FROM Word WHERE Lemma = ${value}")
    }

    static ArrayList<Word> findByComment(value) {
        findBySql("SELECT * FROM Word WHERE Comment = ${value}")
    }



    static ArrayList<Word> findByLemmaLike(String keyword) {
        findBySql("SELECT * FROM Word WHERE Lemma LIKE $keyword")
    }

    static ArrayList<Word> findByCommentLike(String keyword) {
        findBySql("SELECT * FROM Word WHERE Comment LIKE $keyword")
    }



    def updateLemma(value) {
        this.lemma = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Word SET Lemma = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateComment(value) {
        this.comment = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Word SET Comment = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    ArrayList<WordIndex> getWordIndexList() {
        WordIndex.findByWord(this)
    }

    // </editor-fold>
}
